package com.charles.seckillPlatform.controller;

import cn.hutool.core.util.IdUtil;
import com.charles.seckillData.domain.SysLog;
import com.charles.seckillData.domain.SysUser;
import com.charles.seckillData.model.UserLogin;
import com.charles.seckillPlatform.mapper.SysLogMapper;
import com.charles.seckillPlatform.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/log")
public class SysLogController {
    
    @Autowired
    private SysLogMapper sysLogMapper;
    
    @Autowired
    private SysUserMapper sysUserMapper;
    
    // 登录日志
    @PostMapping("/loginRecord")
    public void loginRecord(@RequestBody UserLogin user) {
        SysLog log = new SysLog();
        log.setLog_id(IdUtil.fastSimpleUUID());
        log.setUser_id(user.getUserId());
        log.setLog_type("login");
        log.setMsg("用户：" + user.getUsername() + "登录成功，IP：" + user.getLoginIp());
        sysLogMapper.addLog(log);
        user.getSysUser().setLogin_ip(user.getLoginIp());
        sysUserMapper.updateUserLoginIp(user.getSysUser());
    }

    // 退出登录日志
    @PostMapping("/logoutRecord")
    public void logoutRecord(@RequestBody UserLogin user) {
        SysLog log = new SysLog();
        log.setLog_id(IdUtil.fastSimpleUUID());
        log.setUser_id(user.getSysUser().getUser_id());
        log.setLog_type("exit");
        log.setMsg("用户：" + user.getUsername() + "退出登录，IP：" + user.getLoginIp());
        sysLogMapper.addLog(log);
    }
    
    // 申请日志
    @PostMapping("/applyRecord/{userId}")
    public void applyRecord(@PathVariable("userId") Long userId) {
        SysLog log = new SysLog();
        SysUser sysUser = sysUserMapper.queryUserById(userId);
        log.setLog_id(IdUtil.fastSimpleUUID());
        log.setUser_id(userId);
        log.setLog_type("apply");
        log.setMsg("用户：" + sysUser.getUser_name() + "申请进入秒杀系统，IP：" + sysUser.getLogin_ip());
        sysLogMapper.addLog(log);
    }
    
}
